package com.generalbackend.role.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.generalbackend.common.constants.Constants;
import com.generalbackend.common.util.ClientUtil;
import com.generalbackend.common.util.SnowFlakeIdGeneratorUtil;
import com.generalbackend.common.model.entity.User;
import com.generalbackend.common.model.vo.UserVO;
import com.generalbackend.common.service.IEtoolsUserService;
import com.generalbackend.role.mapper.UserMapper;
import com.generalbackend.role.model.entity.UserRole;
import com.generalbackend.role.model.query.UserQuery;
import com.generalbackend.role.service.IUserRoleService;
import com.generalbackend.role.service.IUserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static com.generalbackend.common.constants.Constants.DATA;
import static com.generalbackend.common.constants.Constants.TOTAL;

/**
* @Description 用户表业务层实现类
* @author tim.xie
* @date 2021-12-16 13:18
*/

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, IEtoolsUserService {
    private Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);

	@Autowired
	private UserMapper userMapper;
    @Autowired
    private PasswordEncoder pw;
    @Autowired
    private IUserRoleService userRoleService;

	@Override
	public Boolean insert(User user) {
	    user.setId(SnowFlakeIdGeneratorUtil.nextId());
	    user.setPassword(pw.encode(Constants.USER_DEFAULT_PASSWORD));
	    user.setCreateUser(ClientUtil.getUser().getId());
	    user.setUpdateUser(ClientUtil.getUser().getId());
        UserRole userRole = new UserRole();
        userRole.setUser(user.getId());
        userRole.setRole(user.getRoleId());
        userRoleService.insert(userRole);
        Integer num = userMapper.insert(user);
        if(num <= 0) {
         return false;
         }
		return true;
	}

	@Override
	public Boolean update(User user) {
	    user.setUpdateUser(ClientUtil.getUser().getId());
        User dbUser = getById(user.getId());
        if (!dbUser.getRoleId().equals(user.getRoleId())) {
            userRoleService.deleteByUserRole(dbUser.getRoleId(), user.getId());
            UserRole userRole = new UserRole();
            userRole.setUser(user.getId());
            userRole.setRole(user.getRoleId());
            userRoleService.insert(userRole);
        }
        Integer num = userMapper.updateById(user);
        if(num <= 0) {
          return false;
        }
		return true;
	}

	@Override
	public Boolean deleteById(String id) {
        userMapper.deleteById(id);
		return true;
	}

	@Override
	public User selectById(String id) {
        User user = userMapper.selectById(id);
        return user;
	}
    @Override
    public JSONObject list(UserQuery userQuery) {
        JSONObject result = new JSONObject();
        Page<User> page = new Page<>(userQuery.getPageNo(), userQuery.getPageSize());
        List<User> userList = userMapper.list(page,userQuery);
        userList.stream().forEach(user -> {
            user.setPassword("");
        });
        result.put(TOTAL,  page.getTotal());
        result.put(DATA, userList);
        return result;
    }

    @Override
    public Boolean exit(Long userId) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getId, userId);
        int count = count(queryWrapper);
        return count > 0 ? true : false;
    }

    @Override
    public User login(String loginIp, String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>().eq(User::getName, username);
        User user = userMapper.selectOne(queryWrapper);
        if (StringUtils.isNotBlank(loginIp)) {
            user.setLoginIp(loginIp);
        }
        user.setLoginTime(new Date());
        userMapper.updateById(user);
        return user;
    }

    @Override
    public boolean resetPassword(Long id) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<User>()
                .set(User::getPassword, pw.encode(Constants.USER_DEFAULT_PASSWORD))
                .eq(User::getId, id);
        return update(updateWrapper);
    }


    @Override
    public UserVO getUserVoById(Long id) {
	    return userMapper.getUserVoById(id);
    }


}
